'use strict';

const fs = require('fs');
const path = require('path');
const jwt = require('jsonwebtoken');
const { Service } = require('egg');

class AccessTokenService extends Service {
/**
 * 生成token
 */
  async createToken(data, expires = 3600) {
    const exp = Math.floor(Date.now() / 1000 + expires);
    const privateKey = fs.readFileSync(path.join(__dirname, '../public/ssh/rsa_private_key.pem')); // 获取私钥
    return jwt.sign({
      data,
      exp,
    }, privateKey, {
      algorithm: 'RS256',
    });
  }

  /**
   * 校验token
   */
  async verifyToken(token) {
    const publicKey = fs.readFileSync(path.join(__dirname, '../public/ssh/rsa_public_key.pem')); // 获取公钥
    let verifyRes;
    try {
      verifyRes = jwt.verify(token, publicKey, {
        algorithm: 'RS256',
      });
    } catch (error) {
      console.log('--------error--------', error);
    }
    return verifyRes;
  }
}

module.exports = AccessTokenService;
